package ota;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import com.ota.fw.FotaClient;
import com.ota.fw.IDownloadEvent;
import com.ota.fw.IHookInstall;
import com.ota.fw.IPkgInfo;
import com.ota.fw.IUpdateInfo;
import com.ota.fw.SysInfo;

import java.io.File;

public class OtaUtils {


    private volatile static OtaUtils mOtaUtils;
    private Activity context;
    private OtaCallBackInterface mOtaCallBackInterface;

    private OtaUtils() {
    }

    public static OtaUtils getOtaUtilsInstance() {
        if (mOtaUtils == null) {
            synchronized (OtaUtils.class) {
                if (mOtaUtils == null) {
                    mOtaUtils = new OtaUtils();
                }
            }
        }

        return mOtaUtils;
    }

    private FotaClient fotaClient;

    /**
     * 检测更新
     */

    public void checkOtaIsNeedUpload(final Activity context, final OtaCallBackInterface mOtaCallBackInterface, String serialNumber, String sourceVersion, String brand, String model) {
        // SysInfo sysInfo = new SysInfo("A7DE830AAATTC0065", "SW01_20161201",
        // "Gmobi", "M001", null);
        this.context=context;
        this.mOtaCallBackInterface=mOtaCallBackInterface;
        fotaClient = FotaClient.buildBasic(context, "https://iot.carota.ai/api/iot/", null, new IHookInstall() {

            @Override
            public int installPackage(Context paramContext, File paramFile) {
                mOtaCallBackInterface.getOtaFilePath(paramFile.toString());
                return 0;
            }
        });

        SysInfo sysInfo = new SysInfo(serialNumber, sourceVersion, brand, model, null);

        IUpdateInfo updateInfo = fotaClient.check(sysInfo);
        if (updateInfo != null) {
            mOtaCallBackInterface.checkOtaIsNeedUpload_Success(updateInfo.getTargetVersion() + "¥" + updateInfo.getSize() + "¥" + updateInfo.getReleaseNote());

        } else {
            System.out.println("失败");
            mOtaCallBackInterface.checkOtaIsNeedUpload_Fail("失败");
        }
    }

    /**
     * 下载内容
     */
    public void download() {
        IPkgInfo packageInfo = fotaClient.download(new IDownloadEvent() {
            @Override
            public void onDownloading(long downloaded, long total, Bundle extra) {
                System.out.println("正在下载中:" + downloaded + " " + total + " ");
            }

            @Override
            public void onDownloaded(Bundle extra) {
                System.out.println("下载成功");
                mOtaCallBackInterface.download_Success("下载成功");

            }

            @Override
            public void onError(int errCode, Bundle extra) {
                System.out.println("下载失败");
                mOtaCallBackInterface.download_Fail("下载失败");

            }
        });
    }

    //	/**
//	 * int resultCode = fotaClient.install();
//	 */
    public void install() {
        int resultCode = fotaClient.install();

    }



}
